/* 
    动态网站练习
*/
const http = require('http');
const path = require('path');
const fs = require('fs');
const querystring = require('querystring');
const resultData = require('./result.json');

http.createServer( (req,res) => {
    // 查询 /query
    if ( req.url.startsWith('/query') && req.method == 'GET' ) {
        fs.readFile(path.join(__dirname,'view','index.html'),'utf8',(err,data)=>{
            if (err) {
                res.write(500,{
                    "Content-Type": "text/plain; charset=utf8"
                });
                res.end('服务器还小差了，请联系管理员');
            }
            res.end(data);
        });
    }
    // 获取 /score
    else if ( req.url.startsWith('/score') && req.method == 'POST' ) {
        let pdata = '';
        req.on('data',(chunk)=>{
            pdata += chunk;
        });
        req.on('end',()=>{
            let obj = querystring.parse(pdata);
            let result = resultData[obj.code];
            fs.readFile(path.join(__dirname,'view','result.html'),'utf8',(err,data)=>{
                if (err) {
                    res.write(500,{
                        "Content-Type" : "text/plain; charset=utf8"
                    })
                    res.end('服务器还小差了，请联系管理员');
                }
                data = data.replace('$$chinese$$', result.chinese);
                data = data.replace('$$math$$', result.math);
                data = data.replace('$$english$$', result.english);
                data = data.replace('$$summary$$',result.summary);

                res.end(data);
            });
        });
    }
}).listen(1000,()=>{
    console.log('running……');
});







